﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CERT.Services.DAL;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
//using WebMatrix.WebData;
using System.Web.Security;
using System.Data.Entity.Migrations;
using WebMatrix.WebData;

namespace CERT.Services
{
    public partial class NETServices
    {
        private System.Configuration.ConnectionStringSettings config;

      

        public void Initialize()
        {
      
            try
            {
                using (var context = new NETEntities())
                {
                    if (!context.Database.Exists())
                    {
                        // Create the SimpleMembership database without Entity Framework migration schema
                        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    }
                }

               /// WebSecurity.InitializeDatabaseConnection(("NETEntities", "UserProfile", "UserId", "UserName", autoCreateTables: true);
              
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
            }
        }


        public UserProfile GetUser(System.Linq.Expressions.Expression<Func<UserProfile, bool>> predicate)
        {
            using (var context = new NETEntities())
            {
               // var entry = context.UserProfiles.Where<UserProfile>(predicate).FirstOrDefault();
                var entry = ((DbSet<UserProfile>)context.UserProfiles).FirstOrDefault<UserProfile>(predicate);
                return entry;

            }
        }

        public void ValidateUser(int id)
        {
            using (var context = new NETEntities())
            {
              //  var entity = context.Set<Lookup>().FirstOrDefault(a => a.LookupID == id);

               // context.Set<Lookup>().Remove(entity);
               // context.SaveChanges();
            }

        }

        public void CreateUserAccount(string userName)
        {
            using (var context = new NETEntities())
            {

                context.UserProfiles.Add(new UserProfile() { UserName = userName });
                context.SaveChanges();
            }
        }

      
        public void DeleteUserAccount(string userName)
        {
            using (var context = new NETEntities())
            {
                var entity = ((DbSet<UserProfile>)context.UserProfiles).FirstOrDefault<UserProfile>(a=>a.UserName == userName);
                context.UserProfiles.Remove(entity);
                context.SaveChanges();
            } 
        }

        //assumes only one role per user
        //no start/end either
        public int GetUserRole(string userName)
        {
            var result = 1;
            using (var context = new NETEntities())
            {
                var entity = context.UserProfiles.Include("webpages_UsersInRoles").FirstOrDefault(a => a.UserName == userName);
                if (entity.webpages_UsersInRoles != null && entity.webpages_UsersInRoles.Count > 0)
                {
                    result = entity.webpages_UsersInRoles.FirstOrDefault().RoleId;
                }
               
            }

            return result;
        }

        //assumes only one role per user
        //no start/end either
        public void DeleteUserRole(string userName)
        {
            var entity = new webpages_UsersInRoles();
            using (var context = new NETEntities())
            {
                entity = ((DbSet<UserProfile>)context.UserProfiles).FirstOrDefault<UserProfile>(a => a.UserName == userName).webpages_UsersInRoles.FirstOrDefault();
                context.webpages_UsersInRoles.Remove(entity);
                context.SaveChanges();
            }

           
        }

        //assumes only one role per user
        //no start/end either
        public void AddUserRole(string userName, int roleId)
        {
            var entity = new webpages_UsersInRoles();
            using (var context = new NETEntities())
            {
                var userprofile = ((DbSet<UserProfile>)context.UserProfiles).FirstOrDefault<UserProfile>(a => a.UserName == userName);
                entity.RoleId = roleId;
                entity.UserId = userprofile.UserId;
                entity.UserProfile = userprofile;

                context.webpages_UsersInRoles.Add(entity);
                context.SaveChanges();
            }


        }


    }



    internal sealed class Configuration : DbMigrationsConfiguration<NETEntities>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(NETEntities context)
        {
            WebSecurity.InitializeDatabaseConnection(
                "DefaultConnection",
                "UserProfile",
                "UserId",
                "UserName", autoCreateTables: true);

            if (!Roles.RoleExists("Administrator"))
                Roles.CreateRole("Administrator");

            if (!Roles.RoleExists("User"))
                Roles.CreateRole("User");

            if (!WebSecurity.UserExists("testAdmin"))
                WebSecurity.CreateUserAndAccount(
                    "testAdmin",
                    "password",
                    new { Mobile = "+9715061000" });

            if (!Roles.GetRolesForUser("testAdmin").Contains("Administrator"))
                Roles.AddUsersToRoles(new[] { "testAdmin" }, new[] { "Administrator" });

            if (!WebSecurity.UserExists("testUser"))
                WebSecurity.CreateUserAndAccount(
                    "testUser",
                    "password",
                    new { Mobile = "+9715061968" });

            if (!Roles.GetRolesForUser("testUser").Contains("User"))
                Roles.AddUsersToRoles(new[] { "testUser" }, new[] { "User" });



        }
    }
}